package com.ruoyi.business.service.impl;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.business.domain.GoodsInfo;
import com.ruoyi.business.domain.OrderInfo;
import com.ruoyi.business.domain.OrderInfoDetail;
import com.ruoyi.business.mapper.GoodsInfoMapper;
import com.ruoyi.business.mapper.OrderInfoDetailMapper;
import com.ruoyi.business.mapper.OrderInfoMapper;
import com.ruoyi.business.service.IGoodsInfoService;
import com.ruoyi.business.utils.BadRequestException;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 商品信息Service业务层处理
 *
 * @author wyb
 * @date 2025-07-11
 */
@Slf4j
@Service
public class GoodsInfoServiceImpl implements IGoodsInfoService {
    @Autowired
    private GoodsInfoMapper goodsInfoMapper;
    @Autowired
    private OrderInfoDetailMapper orderInfoDetailMapper;
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    /**
     * 查询商品信息
     *
     * @param skuBarCode 商品信息主键
     * @return 商品信息
     */
    @Override
    public GoodsInfo selectGoodsInfoBySkuBarCode(String skuBarCode) {
        return goodsInfoMapper.selectGoodsInfoBySkuBarCode(skuBarCode);
    }

    /**
     * 查询商品信息列表
     *
     * @param goodsInfo 商品信息
     * @return 商品信息
     */
    @Override
    public List<GoodsInfo> selectGoodsInfoList(GoodsInfo goodsInfo) {
        return goodsInfoMapper.selectGoodsInfoList(goodsInfo);
    }

    /**
     * 新增商品信息
     *
     * @param goodsInfo 商品信息
     * @return 结果
     */
    @Override
    public int insertGoodsInfo(GoodsInfo goodsInfo) {
        goodsInfo.setCreateTime(DateUtils.getNowDate());
        return goodsInfoMapper.insertGoodsInfo(goodsInfo);
    }

    /**
     * 修改商品信息
     *
     * @param goodsInfo 商品信息
     * @return 结果
     */
    @Override
    public int updateGoodsInfo(GoodsInfo goodsInfo) {
        goodsInfo.setUpdateTime(DateUtils.getNowDate());
        goodsInfo.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        return goodsInfoMapper.updateGoodsInfo(goodsInfo);
    }

    /**
     * 批量删除商品信息
     *
     * @param skuBarCodes 需要删除的商品信息主键
     * @return 结果
     */
    @Override
    public int deleteGoodsInfoBySkuBarCodes(String[] skuBarCodes) {
        /*
        List<String> skuBarCodeList = Arrays.asList(skuBarCodes);
        // 1️⃣ 批量查询：一次查出所有被引用的条码
        List<OrderInfoDetail> orderInfoDetailList = orderInfoDetailMapper.selectBySkuBarCodes(skuBarCodeList);

        // 2️⃣ 找出已被引用的条码,一个商品对应多个订单
        Map<String, List<String>> skuOrderMap = orderInfoDetailList.stream()
                .collect(Collectors.groupingBy(
                        OrderInfoDetail::getSkuBarCode,
                        Collectors.mapping(OrderInfoDetail::getOuterOrderNo, Collectors.toList())
                ));

        // 用于存储无法删除的商品的相关订单信息
        StringBuilder message = new StringBuilder();

        skuOrderMap.forEach((skuBarCode, orderNos) -> {
            // 一个skuBarCode 对应多个orderNos
            List<OrderInfo> orderInfos = orderInfoMapper.selectOrderInfoByOuterOrderNos(orderNos);

            // 状态为 2（生效已发送）、3（已发货）的不能删除
            List<String> cantDelete = orderInfos.stream()
                    .filter(item -> item.getStatus() == 2 || item.getStatus() == 3)
                    .map(OrderInfo::getOuterOrderNo)
                    .collect(Collectors.toList());

            // 3️⃣ 如果有被引用的商品，抛异常
            if (!CollectionUtils.isEmpty(cantDelete)) {
                // 将当前skuBarCode的错误信息添加到message
                message.append("【").append(skuBarCode).append("】关联订单：")
                        .append(cantDelete.stream().collect(Collectors.joining(", ")));
                throw new BadRequestException("商品存在【生效已发送】或【已发货】的关联订单，无法删除：" + message.toString());
            }
        });
        // 4️⃣ 全部安全后删除
        */
        return goodsInfoMapper.deleteGoodsInfoBySkuBarCodes(skuBarCodes);
    }


    /**
     * 删除商品信息信息
     *
     * @param skuBarCode 商品信息主键
     * @return 结果
     */
    @Override
    public int deleteGoodsInfoBySkuBarCode(String skuBarCode) {
        /*String[] skuBarCodes = new String[] { skuBarCode };
        return this.deleteGoodsInfoBySkuBarCodes(skuBarCodes);*/
        return goodsInfoMapper.deleteGoodsInfoBySkuBarCode(skuBarCode);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchInsertOrUpdateByImport(List<GoodsInfo> goodsInfos) {
        String username = SecurityUtils.getLoginUser().getUser().getNickName();
        Date now = DateUtils.getNowDate();
        for (GoodsInfo item : goodsInfos) {
            if (item.getSkuBarCode() == null) {
                throw new BadRequestException("规格条码不能为空！");
            }
            if (item.getCreateTime() == null) {
                item.setCreateTime(now);
            }
            if (StrUtil.isBlank(item.getCreateBy())) {
                item.setCreateBy(username);
            }
            item.setUpdateTime(now);
            item.setUpdateBy(username);
        }

        int batchSize = 1000;
        for (int i = 0; i < goodsInfos.size(); i += batchSize) {
            int end = Math.min(i + batchSize, goodsInfos.size());
            List<GoodsInfo> batchList = goodsInfos.subList(i, end);
            this.batchinsertOrUpdate(batchList);
            //  goodsInfoMapper.insertOrUpdateBatch(batchList);
        }
    }


    @Transactional(rollbackFor = Exception.class)
    public void batchinsertOrUpdate(List<GoodsInfo> batchList) {
        for (GoodsInfo goods : batchList) {
            GoodsInfo existing = goodsInfoMapper.selectGoodsInfoBySkuBarCode(goods.getSkuBarCode());
            if (existing != null) {
                // 存在则更新
                goodsInfoMapper.updateGoodsInfo(goods);
            } else {
                // 不存在则插入
                goodsInfoMapper.insertGoodsInfo(goods);
            }
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public String batchInsert(List<GoodsInfo> goodsInfos) {
        if (goodsInfos == null || goodsInfos.isEmpty()) {
            //0条数据
            return "没有数据,请修改商品号";
        }
        int count = 0;
        List<String> skuBarCodes = goodsInfos.stream()
                .map(GoodsInfo::getSkuBarCode)  // 提取属性
                .filter(Objects::nonNull)  // 过滤掉null值
                .collect(Collectors.toList());
        boolean b = this.checkGoodsSkuBarCodeUnique(skuBarCodes);
        if (b == false) {
            ArrayList<GoodsInfo> existingGoodsList = new ArrayList<>();
            // 遍历微盟中已存在的商品主键，返回根据微盟中主键查询出的集合
            for (String skuBarCode : skuBarCodes) {
                GoodsInfo goodsInfo = goodsInfoMapper.selectGoodsInfoBySkuBarCode(skuBarCode);
                if (goodsInfo != null) {
                    existingGoodsList.add(goodsInfo);
                }
            }
            //从微盟去数据库中唯一的主键id集合
            Set<String> existingSkuBarCodes = new HashSet<>();
            for (GoodsInfo goodsInfo : existingGoodsList) {
                if (goodsInfo != null && !StringUtils.isEmpty(goodsInfo.getSkuBarCode())) {
                    existingSkuBarCodes.add(goodsInfo.getSkuBarCode());
                }
            }
            // 筛选需要新增的数据
            List<GoodsInfo> toInsert = goodsInfos.stream()
                    .filter(goodsInfo -> !existingSkuBarCodes.contains(goodsInfo.getSkuBarCode()))
                    .collect(Collectors.toList());
            //执行补录
            for (GoodsInfo goodsInfo : toInsert) {
                if (!toInsert.isEmpty()) {
                    goodsInfoMapper.insertGoodsInfo(goodsInfo);
                    count++;
                }
            }
            //fixme existingSkuBarCodes 已经存在的要更新
            List<GoodsInfo> toUpdate = goodsInfos.stream()
                    .filter(goodsInfo -> existingSkuBarCodes.contains(goodsInfo.getSkuBarCode()))
                    .collect(Collectors.toList());
            if (!toUpdate.isEmpty()) {
                int updatedCount = goodsInfoMapper.batchUpsertGoodsInfo(toUpdate);
                log.info("批量更新商品信息成功，共更新 {} 条记录", updatedCount);
            } else {
                log.info("没有需要更新的商品信息");
            }

            return "成功补录" + count + "条数据: " + toInsert;
        }
        for (GoodsInfo goodsInfo : goodsInfos) {
            goodsInfoMapper.insertGoodsInfo(goodsInfo);
            count++;
        }
        //返回新增几条数量
        return "成功导入" + count + "条数据: ";
    }


    @Override
    public boolean checkGoodsSkuBarCodeUnique(List<String> skuBarCodes) {
        // StringUtils.isNull(goodsInfo.getSkuBarCode()) ? -1L : goodsInfo.getSkuBarCode();
        List<GoodsInfo> goodsInfos = goodsInfoMapper.checkGoodsInfoUnique(skuBarCodes);
        //没有相同的
        if (goodsInfos.size() == 0) {
            return UserConstants.UNIQUE;
        }
        return UserConstants.NOT_UNIQUE;
    }

}
